"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : 数据库最大连接数为2，查询主备环境可连接个数
Create At   : 2021/01/06
@zou_jialiang0505328126
Description :
    1.创建数据库
    2.创建普通用户
    3.每个节点同时连接3个session
Expect      :
    1.创建数据成功
    2.创建用户成功
    3.每个节点都是连接第3个session异常，提示too many
History     :
    modified: 2021/2/9  modified by @peilinqian,增加主备同步，保证新建用户信息同步至备机
"""

import time
import unittest

from testcase.utils.ComThread import ComThread
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node


class DdlDatabase(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('--Opengauss_Reliability_Dbsys_Case229.py 开始执行--')
        self.pri_dbuser = Node(node='PrimaryDbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.sta_1_sh = CommonSH('Standby1DbUser')
        self.sta_2_sh = CommonSH('Standby2DbUser')
        self.constant = Constant()
        self.db_name = 'database_case229'
        self.tblname = 'tbl_case229'
        self.username = 'user_case229'
        self.password = 'test@2345234'
        self.create_db_sql = f"drop database if exists {self.db_name};" \
            f"create database {self.db_name} with LC_COLLATE='zh_CN.gbk' " \
            f"LC_CTYPE = 'zh_CN.gbk' CONNECTION LIMIT=2;"
        self.create_user_sql = f"drop user if exists {self.username};" \
            f"create user {self.username} with password '{self.password}';"
        self.drop_db_sql = f"drop database if exists {self.db_name};"
        self.drop_user_sql = f"drop user if exists {self.username};"

    def test_basebackup(self):
        self.log.info('-----------1.创建数据库------------')
        result = self.pri_sh.executDbSql(self.create_db_sql)
        self.log.info(result)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS_MSG, result)

        self.log.info('------------2.创建普通用户---------------')
        result = self.pri_sh.executDbSql(self.create_user_sql)
        self.log.info(result)
        self.assertIn(self.constant.CREATE_ROLE, result)
        time.sleep(1)

        self.log.info('------------等待主备同步---------------')
        self.pri_sh.check_location_consistency('primary', 3)

        self.log.info('--------3.每个节点同时连接3个session-------')
        connect_thread = []
        connect_args = f'-U {self.username} -W {self.password}'
        for i in range(9):
            if i < 3:
                connect_thread.append(ComThread(self.pri_sh.executDbSql,
                                                args=('select pg_sleep(30);',
                                                      self.db_name,
                                                      connect_args)))
            elif i > 2 and i < 6:
                connect_thread.append(ComThread(self.sta_1_sh.executDbSql,
                                                args=('select pg_sleep(30);',
                                                      self.db_name,
                                                      connect_args)))
            else:
                connect_thread.append(ComThread(self.sta_2_sh.executDbSql,
                                                args=('select pg_sleep(30);',
                                                      self.db_name,
                                                      connect_args)))
            connect_thread[i].setDaemon(True)
            connect_thread[i].start()
            time.sleep(1)
        for i in range(9):
            connect_thread[i].join(50)
            result = connect_thread[i].get_result()
            self.log.info(result)
            if i == 2 or i == 5 or i == 8:
                self.assertIn('too many', result)
            else:
                self.assertNotIn('too many', result)
        time.sleep(2)

    def tearDown(self):
        self.log.info('---------------环境清理---------')
        self.log.info('----------------------删除数据库----')
        result = self.pri_sh.executDbSql(self.drop_db_sql)
        self.log.info(result)
        self.log.info('----------------------删除用户----')
        result = self.pri_sh.executDbSql(self.drop_user_sql)
        self.log.info(result)
        self.log.info('Opengauss_Reliability_Dbsys_Case229.py 执行结束-')
